import qs from 'qs'

/**
 * 跳转工具类
 */
export function tn(e: any) {
	uni.navigateTo({
		url: e
	})
}
export function tnParamById(e: any, id: any) {
	console.log(id)
	uni.navigateTo({
		url: e + '?id=' + id
	})
}

export function tnParam(e: any, params: any) {
	uni.navigateTo({
		url: e + '?' + qs.stringify(params, { indices: false }),
	})
}

/**
 * 跳转工具类 uniapp关闭页面进入新页面
 * redirectTo
 *
 */
export function tnRed(e: any) {
	uni.redirectTo({
		url: e
	})
}
export function tnRedById(e: any, id: any) {
	uni.redirectTo({
		url: e + '?id=' + id
	})
}

export function tnRedParam(e: any, params: any) {
	uni.redirectTo({
		url: e + '?' + qs.stringify(params, { indices: false }),
	})
}

/**
 * 跳转工具类 uniapp关闭当前页面,打开新
 * reLaunch
 */
export function tnRel(e: any) {
	uni.reLaunch({
		url: e
	})
}
export function tnRelById(e: any, id: any) {
	uni.reLaunch({
		url: e + '?id=' + id
	})
}

export function tnRelParam(e: any, params: any) {
	uni.reLaunch({
		url: e + '?' + qs.stringify(params, { indices: false }),
	})
}


export function goBack() {
	// 点击左上角返回按钮时触发事件

	// 通过判断当前页面的页面栈信息，是否有上一页进行返回，如果没有则跳转到首页

	const pages = getCurrentPages();

	if (pages && pages.length > 0) {
		const firstPage = pages[0];
		console.log("firstPage=>", firstPage, firstPage.route);
		if (pages.length == 1 && (!firstPage.route || firstPage.route != "pages/index")) {
			uni.reLaunch({
				url: "/pages/index/index",
			});
		} else {
			const prevPage = pages[pages.length - 2]; // 获取上一页的页面对象
			console.log("prevPage=>", prevPage, prevPage.route);
			if (prevPage && prevPage.route == "pages/index") {
				// prevPage.$vm.onLoad(); // 调用上一页的onLoad方法，用于刷新数据
				uni.navigateBack({
					delta: 1,
					success: (event) => {
						// prevPage.$vm._switchTabbarPage(prevPage.$vm.currentIndex);
					},
				});
			} else {
				uni.navigateBack({
					delta: 1,
					success: (event) => {
						// prevPage.$vm.init();
					},
				});
			}
			// let currentPage = pages[pages.length-1]
			// this.initData();
		}
	} else {
		uni.reLaunch({
			url: "/pages/index/index",
		});
	}
}
export default {
	goBack,
	tn,
	tnParam,
	tnParamById,
	tnRed,
	tnRedParam,
	tnRedById,
	tnRel,
	tnRelParam,
	tnRelById
}
